package com.luculent.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.MessageDigest;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EncryptUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(EncryptUtils.class);
    
	private static ScriptEngineManager mgr = new ScriptEngineManager();
	private static ScriptEngine engine ;
	
	public static String mD5(String str) {  
        try {  
            // 生成一个MD5加密计算摘要  
            MessageDigest md = MessageDigest.getInstance("MD5");  
            // 计算md5函数  
            md.update(str.getBytes());  
            return  byteArrayToHexString(md.digest()); 
        } catch (Exception e) {  
           e.printStackTrace();  
           return null;  
        }  
    }  
	private static String byteArrayToHexString(byte[] b) {  
	    StringBuilder hs = new StringBuilder();     
	    String stmp;      
		for (int n = 0; b!=null && n < b.length; n++) {   
		       stmp = Integer.toHexString(b[n] & 0XFF);    
		       if (stmp.length() == 1)           
		       hs.append('0');      
		       hs.append(stmp);    
		  }      
		 return hs.toString().toLowerCase();   
	}
	
	public static String readFile()throws Exception{
		 
        BufferedReader bReader = new BufferedReader(new InputStreamReader(EncryptUtils.class.getResourceAsStream("aes.js")));//new一个BufferedReader对象，将文件内容读取到缓存
        StringBuilder sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
        String s = "";
        while ((s =bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
            sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中 
        }
        bReader.close();
        String str = sb.toString(); 
        return str;
	} 
	public static Invocable getAesEngine() throws Exception{
		if(engine == null){
			engine = mgr.getEngineByName("JavaScript");
			//getIwResource得到资源
			String descon = new String(readFile());
			engine.eval(descon);
		}
		return (Invocable)engine;
	}
	
	//加密
	public static  String sha256_HMAC(String message, String secret) {     
		   String hash = "";      
		   try {         
		       Mac sha256_HMAC = Mac.getInstance("HmacSHA256");     
		       SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");      
		       sha256_HMAC.init(secret_key);       
		       byte[] bytes = sha256_HMAC.doFinal(message.getBytes());   
		       hash = byteArrayToHexString(bytes);         
		       log.debug(hash);    
	       } catch (Exception e) {     
	    	   logger.debug("Error HmacSHA256 ===========" + e.getMessage());   
	       }       
		    return hash;   
	}   
}

